package middleware

import (
	"fmt"
	"log/slog"
	"time"

	"github.com/gin-gonic/gin"
)

// LoggerMiddleware 日志中间件
func LoggerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		// 处理请求
		c.Next()
		end := time.Now()

		mothod := c.Request.Method
		path := c.Request.URL.Path
		code := c.Writer.Status()
		latency := end.Sub(start)
		ip := c.ClientIP()

		// 添加默认日志字段
		logger := slog.With("module", "GIN")

		// 日志记录
		if code < 400 { // 状态码 200-399 表示正常请求
			logger.Info("正常请求",
				slog.String("mothod", mothod),
				slog.Int("code", code),
				slog.String("path", path),
				slog.String("latency", formatDuration(latency)),
				slog.String("ip", ip),
			)
		} else {
			logger.Error("错误请求",
				slog.String("mothod", mothod),
				slog.Int("code", code),
				slog.String("path", path),
				slog.String("latency", formatDuration(latency)),
				slog.String("ip", ip),
			)
		}
	}
}

// 格式化时间
func formatDuration(d time.Duration) string {
	if d < time.Microsecond { // 当时间小于1微秒时, 以纳秒为单位
		return fmt.Sprintf("%d ns", d.Nanoseconds())
	} else if d < time.Millisecond { // 当时间小于1毫秒时, 以微秒为单位
		return fmt.Sprintf("%.3f µs", float64(d.Nanoseconds())/float64(time.Microsecond))
	} else if d < time.Second { // 当时间小于1秒时, 以毫秒为单位
		return fmt.Sprintf("%.3f ms", float64(d.Nanoseconds())/float64(time.Millisecond))
	}
	return fmt.Sprintf("%.3f s", d.Seconds())
}
